<template>
  <page-container title="数据采集管理">
  <div class="data-collect-list">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="openEditDialog()">新增采集配置</el-button>
      <el-input
      v-model="searchId"
      placeholder="请输入数据采集配置ID"
      clearable
      @clear="handleSearch"
      style="width: 250px; margin-left: 10px"
      @keyup.native.enter="handleSearch"
      >
        <template #append>
          <el-button icon="el-icon-search" @click="handleSearch" />
        </template>
      </el-input>
    </div>

    <!-- 数据采集配置表格 -->
    <el-table
    :data="configList"
    style="width: 100%"
    :fit="true"
    :border="true"
    v-loading="loading"
    header-height="50"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="配置名称" min-width="120" />
      <el-table-column label="数据源" min-width="100">
        <template slot-scope="scope">
          {{ getDataSourceName(scope.row.dataSourceId) }}
        </template>
      </el-table-column>
      <el-table-column prop="tableName" label="目标表名" min-width="150" />
      <el-table-column prop="whereClause" label="筛选条件" show-overflow-tooltip min-width="200">
        <template slot-scope="scope">
          <el-tooltip effect="dark" :content="scope.row.whereClause || '无'" placement="top">
            <span>{{ (scope.row.whereClause || '无').length > 30 ? (scope.row.whereClause.slice(0, 30) + '...') : (scope.row.whereClause || '无') }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="enablePreview" label="启用预览" min-width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.enablePreview === 1 ? 'success' : 'info'">
            {{ scope.row.enablePreview === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="150" />
      <el-table-column label="操作" width="240" flex="right" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handlePreview(scope.row)" :disabled="scope.row.enablePreview !== 1">预览</el-button>
          <el-button size="mini" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="850px"
      @close="resetForm"
    >
    <!-- 分步选择 -->
      <el-steps :active="activeStep" finish-status="success" simple style="margin-bottom: 20px;">
        <el-step title="基础信息配置"></el-step>
        <el-step title="字段选择与筛选"></el-step>
        <el-step title="数据预览"></el-step>
      </el-steps>
      <!-- 基础信息配置 -->
       <div v-if="activeStep === 0">
        <el-form :model="form" :rules="rules" ref="configForm" label-width="120px">
          <el-form-item label="配置名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入配置名称（最多100个字符）"></el-input>
          </el-form-item>
          <el-form-item label="数据源" prop="dataSourceId" >
            <el-select
            v-model="form.dataSourceId"
            placeholder="请选择数据源"
            style="width: 100%;">
              <el-option
              v-for="item in dataSourceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"></el-option>
            </el-select>
            <el-button
            v-if="form.dataSourceId"
            type="text"
            style="margin-left: 10px;"
            @click="refreshTableMetadata">
              刷新元数据
            </el-button>
          </el-form-item>
          <el-form-item label="表名" prop="tableName">
            <el-select
              v-model="form.tableName"
              filterable
              placeholder="请选择表名"
              style="width: 100%;"
              :loading="tableLoading"
              @change="handleTableChange">
              <el-option
                v-for="table in tableOptions"
                :key="table"
                :label="table"
                :value="table">
                <span>{{ table }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="启用预览" prop="enablePreview">
            <el-switch
              v-model="form.enablePreview"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用">
            </el-switch>
            <span class="status-tip">（启用后可以预览数据）</span>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息(可选)"></el-input>
          </el-form-item>

        </el-form>
       </div>
       <!-- 字段选择与筛选 -->
       <div v-if="activeStep === 1">
        <el-form label-width="120px">
          <el-form-item label="字段选择">
            <div class="column-selection">
              <div class="column-header">
                <el-checkbox
                  :indeterminate="isIndeterminate"
                  v-model="checkAll"
                  @change="handleCheckAllChange">
                  全选/取消全选
                </el-checkbox>
              </div>
              <div class="column-list">
                <el-checkbox-group v-model="form.selectedColumns" @change="handleCheckedColumnsChange">
                  <el-checkbox
                    v-for="column in columnOptions"
                    :key="column.id"
                    :label="column.columnName">
                    <span>{{ column.columnName }}</span>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="WHERE条件" prop="whereClause">
            <el-input
              v-model="form.whereClause"
              type="textarea"
              :rows="3"
              @blur="validateWhereClause"
              placeholder="请输入SQL WHERE条件，如：create_time > '2023-01-01'（可选）">
            </el-input>
            <div v-if="whereClauseError" class="error-message">{{ whereClauseError }}</div>
            <div class="where-tips">
              <p>提示：</p>
              <ul>
                <li>条件格式：字段名 操作符 值，如 price &gt; 100</li>
                <li>多个条件用AND/OR连接，如 price &gt; 100 AND stock &gt; 0</li>
                <li>字符串需要用单引号，如 name = 'test'</li>
                <li>支持的操作符：=, &gt;, &lt;, &gt;=, &lt;=, &lt;&gt;, LIKE, IN, IS NULL</li>
              </ul>
            </div>
          </el-form-item>
          <el-form-item label="排序字段">
            <el-select v-model="form.orderByColumn" placeholder="请选择排序字段（可选）" style="width: 50%;">
              <el-option
                v-for="column in columnOptions"
                :key="column.id"
                :label="column.columnName"
                :value="column.columnName">
              </el-option>
            </el-select>
            <el-select v-model="form.orderDirection" placeholder="排序方向" style="width: 30%; margin-left: 10px;">
              <el-option label="升序" value="ASC"></el-option>
              <el-option label="降序" value="DESC"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
       </div>
      <!-- 第三步：数据预览 -->
      <div v-if="activeStep === 2">
        <div class="preview-header">
          <el-button type="primary" size="small" @click="loadPreviewData" :loading="previewLoading">刷新预览</el-button>
          <span class="preview-count" v-if="previewTotal !== null">总记录数: {{ previewTotal }}</span>
        </div>
        <el-table
          :data="previewData"
          border
          v-loading="previewLoading"
          style="width: 100%; margin-top: 10px;"
          max-height="400px">
          <el-table-column
            v-for="column in previewColumns"
            :key="column"
            :prop="column"
            :label="column"
            show-overflow-tooltip>
          </el-table-column>
        </el-table>
        <div class="preview-pagination" v-if="previewTotal > 0">
          <el-pagination
            @size-change="handlePreviewSizeChange"
            @current-change="handlePreviewCurrentChange"
            :current-page="form.previewCurrentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="form.previewPageSize"
            layout="total, sizes, prev, pager, next"
            :total="previewTotal">
          </el-pagination>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="prevStep" v-if="activeStep > 0">上一步</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="activeStep < 2" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-if="activeStep === 2" type="primary" @click="submitForm" :loading="submitLoading">保 存</el-button>
      </div>
  </el-dialog>

    <!-- 数据预览对话框 -->
    <el-dialog
      title="数据预览"
      :visible.sync="previewDialogVisible"
      width="90%">
      <div class="preview-header">
        <span class="preview-count" v-if="previewTotal !== null">总记录数: {{ previewTotal }}</span>
      </div>
      <el-table
        :data="previewData"
        border
        v-loading="previewLoading"
        style="width: 100%; margin-top: 10px;"
        max-height="600px">
        <el-table-column
          v-for="column in previewColumns"
          :key="column"
          :prop="column"
          :label="column"
          show-overflow-tooltip>
        </el-table-column>
      </el-table>
      <div class="preview-pagination" v-if="previewTotal > 0">
        <el-pagination
          @size-change="handlePreviewSizeChange"
          @current-change="handlePreviewCurrentChange"
          :current-page="form.previewCurrentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="form.previewPageSize"
          layout="total, sizes, prev, pager, next"
          :total="previewTotal">
        </el-pagination>
      </div>
    </el-dialog>

  </div>
  </page-container>
</template>
<script>
import PageContainer from '@/components/PageContainer.vue'
import { getDataSourceList } from '@/api/source'
import {
  deleteDataCollectConfig,
  addDataCollectConfig,
  updateDataCollectConfig,
  getDataCollectConfigList,
  getDataCollectConfigById,
  getTableList,
  getColumnList,
  refreshMetadata,
  previewData,
  countRecords
} from '@/api/collection'
export default {
  name: 'DataCollectList',
  components: {
    PageContainer
  },
  data () {
    return {
      // 配置列表数据
      configList: [],
      searchId: '', // 搜索数据源ID
      loading: false, // 加载状态
      total: 0, // 总条数
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      dialogVisible: false, // 编辑弹窗是否可见
      dialogTitle: '添加数据采集配置',
      submitLoading: false,
      activeStep: 0,
      // 数据源选项
      dataSourceOptions: [],

      // 表和字段选项
      tableOptions: [],
      tableLoading: false,
      columnOptions: [],
      columnLoading: false,

      // 字段选择相关
      checkAll: false,
      isIndeterminate: false,

      // 数据预览相关
      previewData: [],
      previewColumns: [],
      previewTotal: null,
      previewLoading: false,
      previewDialogVisible: false,

      // 表单数据 - 增强版
      form: {
        id: null,
        name: '',
        dataSourceId: '',
        tableName: '',
        whereClause: '',
        enablePreview: 1,
        remark: '',
        // 新增字段
        selectedColumns: [], // 选中的字段
        orderByColumn: '', // 排序字段
        orderDirection: 'ASC', // 排序方向
        previewPageSize: 10, // 预览分页大小
        previewCurrentPage: 1 // 预览当前页
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入配置名称', trigger: 'blur' },
          { max: 100, message: '配置名称长度不能超过100个字符', trigger: 'blur' }
        ],
        dataSourceId: [
          { required: true, message: '请选择数据源', trigger: 'change' }
        ],
        tableName: [
          { required: true, message: '请选择表名', trigger: 'change' }
        ]
      },
      // 新增的验证逻辑
      whereClauseError: '',
      whereClauseTips: {
        price: {
          operator: '>',
          value: '100'
        },
        stock: {
          operator: '>',
          value: '0'
        }
      }
    }
  },
  created () {
    this.loadData()
    this.getDataSources()
  },
  methods: {
    // 加载数据
    async loadData () {
      this.loading = true
      try {
        const params = {
          current: this.currentPage,
          size: this.pageSize,
          id: this.searchId || undefined
        }
        if (this.searchId) {
          const res = await getDataCollectConfigById(this.searchId)
          console.log('查询数据res', res)
          if (res.code === 200 && res.data) {
            this.configList = [res.data]
            this.total = 1
          } else {
            this.configList = []
            this.total = 0
            this.$message.warning(res.msg || '未找到该数据采集配置ID的数据')
          }
        } else {
          const res = await getDataCollectConfigList(params)
          console.log('查询数据res', res)
          if (res.code === 200) {
            this.configList = res.data.records || []
            this.total = res.data.total || 0
          } else {
            this.$message.error(res.msg || '获取数据采集配置列表失败')
            // 在接口失败时初始化为空数组，避免前端报错
            this.configList = []
            this.total = 0
          }
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据采集配置列表失败: ' + (error.message || '未知错误'))
        // 在接口异常时初始化数据，避免界面报错
        this.configList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    // 打开新增采集配置弹窗
    async openEditDialog (row) {
      if (row) {
        // 有id是编辑
        this.dialogTitle = '编辑数据采集配置'
        this.dialogVisible = true
        this.activeStep = 0

        try {
          const res = await getDataCollectConfigById(row.id)
          if (res.code === 200) {
            const data = res.data
            // 填充基本表单数据
            this.form = {
              id: data.id,
              name: data.name,
              dataSourceId: data.dataSourceId,
              tableName: data.tableName,
              whereClause: data.whereClause || '',
              enablePreview: data.enablePreview,
              remark: data.remark || '',
              // 增强字段 - 如果后端返回了这些字段则使用，否则使用默认值
              selectedColumns: data.selectedColumns || [],
              orderByColumn: data.orderByColumn || '',
              orderDirection: data.orderDirection || 'ASC',
              previewPageSize: data.previewPageSize || 10,
              previewCurrentPage: 1
            }

            // 如果已选择数据源，加载表和字段
            if (this.form.dataSourceId) {
              await this.getTables(this.form.dataSourceId)
              if (this.form.tableName) {
                await this.getColumns(this.form.dataSourceId, this.form.tableName)

                // 如果没有特定选中字段，默认选中所有字段
                if (!this.form.selectedColumns || this.form.selectedColumns.length === 0) {
                  this.form.selectedColumns = this.columnOptions.map(column => column.columnName)
                  this.checkAll = true
                  this.isIndeterminate = false
                } else {
                // 否则设置部分选中状态
                  this.checkAll = this.form.selectedColumns.length === this.columnOptions.length
                  this.isIndeterminate = this.form.selectedColumns.length > 0 && this.form.selectedColumns.length < this.columnOptions.length
                }
              }
            }
          }
        } catch (error) {
          console.error('获取数据采集配置失败', error)
          this.$message.error('获取数据采集配置失败: ' + (error.message || '未知错误'))
        }
      } else {
        // 没有id是新增
        this.dialogTitle = '添加数据采集配置'
        this.dialogVisible = true
        this.activeStep = 0
        this.resetForm()
        // 检查数据源选项是否已加载
        if (this.dataSourceOptions.length === 0) {
          this.getDataSources().then(() => {
            if (this.dataSourceOptions.length === 0) {
              this.$message.warning('未获取到数据源，请先添加数据源')
            }
          })
        }
      }
    },
    // 删除数据
    async handleDelete (row) {
      this.$confirm('确认删除该配置？', '温馨提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        try {
          const res = await deleteDataCollectConfig(row.id)
          if (res.code === 200) {
            this.$message.success('删除成功！')
            this.loadData()
          } else {
            this.$message.error('删除失败：' + (res.msg || '未知错误'))
          }
        } catch (error) {
          console.error('删除数据采集配置失败：', error)
          this.$message.error('删除失败：' + (error.message || '未知错误'))
        }
      })
    },

    // 获取数据源列表（用于添加数据源时下拉选择）
    async getDataSources () {
      try {
        const res = await getDataSourceList({
          current: 1,
          size: 10 // 获取更多数据源
        })

        if (res.code === 200) {
          this.dataSourceOptions = res.data.records || []
        } else {
          this.$message.error(res.msg || '获取数据源列表失败')
          this.dataSourceOptions = []
        }
      } catch (error) {
        console.error('获取数据源列表出错', error)
        this.$message.error('获取数据源列表失败: ' + (error.message || '未知错误'))
        this.dataSourceOptions = []
      }
    },
    // 获取数据源名称
    getDataSourceName (dataSourceId) {
      const source = this.dataSourceOptions.find(item => item.id === dataSourceId)
      return source ? source.name : dataSourceId
    },
    // 获取表列表
    async getTables (dataSourceId) {
      this.tableLoading = true
      try {
        console.log('开始获取表列表，数据源ID:', dataSourceId)
        const res = await getTableList(dataSourceId)
        console.log('获取表列表响应:', res)

        if (res.code === 200) {
          if (res.data && Array.isArray(res.data) && res.data.length > 0) {
            // 后端返回的是字符串列表而非对象数组，直接使用
            this.tableOptions = res.data
            console.log('获取到表列表，共', res.data.length, '个表:', res.data)
          } else {
            this.tableOptions = []
            this.$message.warning('未获取到任何表，请检查数据源配置或联系管理员')
            console.warn('获取表列表成功，但数据为空')
          }
        } else {
          this.tableOptions = []
          this.$message.error(res.msg || '获取表列表失败')
        }
      } catch (error) {
        console.error('获取表列表出错', error)
        this.tableOptions = []
        this.$message.error('获取表列表失败: ' + (error.message || '未知错误'))
      } finally {
        this.tableLoading = false
      }
    },
    // 获取字段列表
    async getColumns (dataSourceId, tableName) {
      this.columnLoading = true
      try {
        console.log('开始获取字段列表，数据源ID:', dataSourceId, '表名:', tableName)
        const res = await getColumnList({
          dataSourceId,
          tableName
        })
        console.log('获取字段列表响应:', res)

        if (res.code === 200) {
          if (res.data && Array.isArray(res.data) && res.data.length > 0) {
            // 后端返回DatabaseMetadata对象列表，直接使用
            this.columnOptions = res.data
            console.log('获取到字段列表，共', res.data.length, '个字段:', res.data)
          } else {
            this.columnOptions = []
            this.$message.warning('未获取到任何字段，请检查表配置或刷新元数据')
            console.warn('获取字段列表成功，但数据为空')
          }
        } else {
          this.columnOptions = []
          this.$message.error(res.msg || '获取字段列表失败')
        }
      } catch (error) {
        console.error('获取字段列表出错', error)
        this.columnOptions = []
        this.$message.error('获取字段列表失败: ' + (error.message || '未知错误'))
      } finally {
        this.columnLoading = false
      }
    },
    // 获取记录总数
    async getRecordCount () {
      try {
        const res = await countRecords({
          dataSourceId: this.form.dataSourceId,
          tableName: this.form.tableName,
          whereClause: this.form.whereClause
        })

        if (res.code === 200) {
          this.previewTotal = res.data || 0
        } else {
          this.$message.warning(res.msg || '获取记录总数失败')
          this.previewTotal = 0
        }
      } catch (error) {
        console.error('获取记录总数出错', error)
        this.$message.warning('获取记录总数失败: ' + (error.message || '未知错误'))
        this.previewTotal = 0
      }
    },

    // 表变更
    async handleTableChange (value) {
      console.log('表名变更为:', value)
      this.columnOptions = []
      this.form.selectedColumns = []

      if (value) {
        try {
          await this.getColumns(this.form.dataSourceId, value)

          // 检查是否成功获取到字段列表
          if (this.columnOptions.length === 0) {
            this.$message.warning('未获取到字段信息，请刷新元数据')
          } else {
            // 默认选中所有字段
            this.form.selectedColumns = this.columnOptions.map(column => column.columnName)
            this.checkAll = true
            this.isIndeterminate = false
          }
        } catch (error) {
          console.error('表变更处理出错', error)
        }
      }
    },
    // 数据源变更
    async handleDataSourceChange (value) {
      console.log('数据源变更为:', value)
      this.form.tableName = ''
      this.tableOptions = []
      this.columnOptions = []
      this.form.selectedColumns = []

      if (value) {
        try {
          // 加载表列表
          await this.getTables(value)

          // 检查是否成功获取到表列表
          if (this.tableOptions.length === 0) {
            this.$confirm('未获取到表列表，是否刷新元数据?', '提示', {
              confirmButtonText: '刷新',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.refreshTableMetadata()
            }).catch(() => {
              // 用户取消刷新
            })
          }
        } catch (error) {
          console.error('数据源变更处理出错', error)
        }
      }
    },
    // 字段选择变化
    handleCheckedColumnsChange (value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.columnOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.columnOptions.length
    },

    // 步骤控制
    prevStep () {
      if (this.activeStep > 0) {
        this.activeStep--
      }
    },
    async nextStep () {
      if (this.activeStep === 0) {
        // 验证第一步表单
        try {
          await this.$refs.configForm.validate()

          // 如果还没有加载表信息，加载表信息
          if (this.form.dataSourceId && this.tableOptions.length === 0) {
            await this.getTables(this.form.dataSourceId)
          }

          // 如果还没有加载字段信息，加载字段信息
          if (this.form.tableName && this.columnOptions.length === 0) {
            await this.getColumns(this.form.dataSourceId, this.form.tableName)
            // 默认选中所有字段
            if (this.form.selectedColumns.length === 0) {
              this.form.selectedColumns = this.columnOptions.map(column => column.name)
              this.checkAll = true
              this.isIndeterminate = false
            }
          }

          this.activeStep++
        } catch (error) {
          // 表单验证失败
          console.error('表单验证失败', error)
          this.$message.warning('请完成必填项')
        }
      } else if (this.activeStep === 1) {
        // 检查是否选择了字段
        if (this.form.selectedColumns.length === 0) {
          this.$message.warning('请至少选择一个字段')
          return
        }

        try {
          // 加载预览数据
          await this.loadPreviewData()
          this.activeStep++
        } catch (error) {
          console.error('加载预览数据失败', error)
          this.$message.error('预览数据加载失败，但您仍然可以继续')
          this.activeStep++
        }
      }
    },
    // 刷新元数据
    async refreshTableMetadata () {
      if (!this.form.dataSourceId) {
        this.$message.warning('请先选择数据源')
        return
      }

      try {
        this.$message.info('正在刷新元数据，请稍候...')
        console.log('开始刷新元数据，数据源ID:', this.form.dataSourceId)
        const res = await refreshMetadata(this.form.dataSourceId)
        console.log('刷新元数据响应:', res)

        if (res.code === 200) {
          this.$message.success('元数据刷新成功')
          // 重新加载表列表
          await this.getTables(this.form.dataSourceId)

          // 如果已选择表，重新加载字段列表
          if (this.form.tableName) {
            await this.getColumns(this.form.dataSourceId, this.form.tableName)

            // 刷新字段选择
            if (this.form.selectedColumns.length > 0) {
              // 过滤掉已不存在的字段
              const validColumns = this.columnOptions.map(column => column.columnName)
              this.form.selectedColumns = this.form.selectedColumns.filter(col => validColumns.includes(col))

              // 更新全选状态
              this.checkAll = this.form.selectedColumns.length === this.columnOptions.length
              this.isIndeterminate = this.form.selectedColumns.length > 0 && this.form.selectedColumns.length < this.columnOptions.length
            } else {
              // 默认选中所有字段
              this.form.selectedColumns = this.columnOptions.map(column => column.columnName)
              this.checkAll = true
              this.isIndeterminate = false
            }
          }
        } else {
          this.$message.error(res.msg || '元数据刷新失败')
        }
      } catch (error) {
        console.error('刷新元数据出错', error)
        this.$message.error('元数据刷新失败: ' + (error.message || '未知错误'))
      }
    },
    // 数据搜索
    handleSearch () {
      // 重置到第一页
      this.currentPage = 1
      console.log('searchId', this.searchId)
      // 验证输入的id是否为数字
      if (this.searchId && !/^\d+$/.test(this.searchId)) {
        this.$message.warning('请输入正确的数据采集配置ID')
        return
      }
      // 加载数据
      this.loadData()
      // this.currentPage = 1
      // this.loadData()
    },
    // 分页处理
    handleSizeChange (size) {
      this.pageSize = size
      this.currentPage = 1
      this.loadData()
    },
    handleCurrentChange (page) {
      this.currentPage = page
      this.loadData()
    },

    // 加载预览数据
    async loadPreviewData () {
      if (!this.form.dataSourceId || !this.form.tableName) {
        this.$message.warning('请先选择数据源和表')
        return
      }

      if (this.form.selectedColumns.length === 0) {
        this.$message.warning('请至少选择一个字段')
        return
      }

      // 如果有WHERE条件，先进行验证
      if (this.form.whereClause && !this.validateWhereClause()) {
        this.$message.warning('WHERE条件有误，请修正后再预览')
        return
      }

      this.previewLoading = true
      this.previewData = []
      this.previewColumns = []

      try {
        // 构建预览请求数据
        const previewRequest = {
          dataSourceId: this.form.dataSourceId,
          tableName: this.form.tableName,
          selectedColumns: this.form.selectedColumns,
          whereClause: this.form.whereClause,
          orderByColumn: this.form.orderByColumn,
          orderDirection: this.form.orderDirection,
          previewPageSize: this.form.previewPageSize,
          previewCurrentPage: this.form.previewCurrentPage
        }

        // 获取数据总数
        await this.getRecordCount()

        // 获取预览数据
        const res = await previewData(previewRequest)

        if (res.code === 200) {
          this.previewData = res.data.rows || []
          this.previewColumns = res.data.columns || []
        } else {
          this.$message.error(res.msg || '数据预览失败')
          this.previewData = []
          this.previewColumns = []
        }
      } catch (error) {
        console.error('数据预览出错', error)
        this.$message.error('数据预览失败: ' + (error.message || '未知错误'))
        this.previewData = []
        this.previewColumns = []
        this.previewTotal = 0
      } finally {
        this.previewLoading = false
      }
    },
    // 预览数据分页
    handlePreviewSizeChange (size) {
      this.form.previewPageSize = size
      this.loadPreviewData()
    },
    handlePreviewCurrentChange (page) {
      this.form.previewCurrentPage = page
      this.loadPreviewData()
    },
    // 打开预览对话框
    async handlePreview (row) {
      // 加载配置
      try {
        const res = await getDataCollectConfigById(row.id)
        if (res.code === 200) {
          const data = res.data

          // 预览表单，只保留需要的字段
          this.form = {
            id: data.id,
            dataSourceId: data.dataSourceId,
            tableName: data.tableName,
            whereClause: data.whereClause || '',
            selectedColumns: data.selectedColumns || [],
            orderByColumn: data.orderByColumn || '',
            orderDirection: data.orderDirection || 'ASC',
            previewPageSize: 10,
            previewCurrentPage: 1
          }

          // 如果没有特定选中字段，需要加载所有字段
          if (!this.form.selectedColumns || this.form.selectedColumns.length === 0) {
            await this.getColumns(this.form.dataSourceId, this.form.tableName)
            this.form.selectedColumns = this.columnOptions.map(column => column.columnName)
          }

          this.previewDialogVisible = true
          this.loadPreviewData()
        }
      } catch (error) {
        console.error('获取数据采集配置详情出错', error)
        this.$message.error('获取数据采集配置详情失败')
      }
    },

    // 重置表单
    resetForm () {
      if (this.$refs.configForm) {
        this.$refs.configForm.resetFields()
      }

      this.form = {
        id: null,
        name: '',
        dataSourceId: '',
        tableName: '',
        whereClause: '',
        enablePreview: 1,
        remark: '',
        selectedColumns: [],
        orderByColumn: '',
        orderDirection: 'ASC',
        previewPageSize: 10,
        previewCurrentPage: 1
      }

      this.activeStep = 0
      this.tableOptions = []
      this.columnOptions = []
      this.previewData = []
      this.previewColumns = []
      this.previewTotal = null
    },
    // 提交表单
    submitForm () {
      if (this.activeStep === 2) {
        this.saveConfigForm()
      } else {
        this.$refs.configForm.validate(valid => {
          if (valid) {
            this.saveConfigForm()
          }
        })
      }
    },
    // 保存配置表单
    async saveConfigForm () {
      try {
        // 先验证WHERE语句
        if (this.form.whereClause && !this.validateWhereClause()) {
          this.$message.error('WHERE条件有误，请修正后再提交')
          if (this.activeStep !== 1) {
            this.activeStep = 1 // 切换到字段与筛选步骤
          }
          return
        }

        this.submitLoading = true

        // 构建提交的数据，使用增强的DTO
        const configDTO = {
          id: this.form.id,
          name: this.form.name,
          dataSourceId: this.form.dataSourceId,
          tableName: this.form.tableName,
          whereClause: this.form.whereClause,
          enablePreview: this.form.enablePreview,
          remark: this.form.remark,
          // 增强的字段
          selectedColumns: this.form.selectedColumns,
          orderByColumn: this.form.orderByColumn,
          orderDirection: this.form.orderDirection
        }

        let res
        if (this.form.id) {
          // 更新
          res = await updateDataCollectConfig(configDTO)
        } else {
          // 新增
          res = await addDataCollectConfig(configDTO)
        }
        console.log('提交表单响应:', res)

        if (res.code === 200) {
          this.$message.success(this.form.id ? '修改成功' : '添加成功')
          this.dialogVisible = false
          this.loadData()
        } else {
          this.$message.error(res.msg || (this.form.id ? '修改失败' : '添加失败'))
        }
      } catch (error) {
        console.error(this.form.id ? '修改数据采集配置出错' : '添加数据采集配置出错', error)
        this.$message.error(this.form.id ? '修改失败' : '添加失败')
      } finally {
        this.submitLoading = false
      }
    },

    // 全选/取消全选
    handleCheckAllChange (val) {
      this.form.selectedColumns = val ? this.columnOptions.map(column => column.columnName) : []
      this.isIndeterminate = false
    },
    // 新增的验证逻辑
    validateWhereClause () {
      // 如果没有填写WHERE条件，则视为有效
      if (!this.form.whereClause || this.form.whereClause.trim() === '') {
        this.whereClauseError = ''
        return true
      }

      // 检查SQL注入风险关键字
      const sqlInjectionKeywords = [
        'DELETE', 'DROP', 'UPDATE', 'INSERT', 'TRUNCATE',
        'ALTER', 'EXEC', 'EXECUTE', '--', '/*', '*/',
        'UNION', 'SELECT', 'INTO', 'SLEEP', 'BENCHMARK'
      ]

      const containsInjection = sqlInjectionKeywords.some(keyword =>
        this.form.whereClause.toUpperCase().includes(keyword)
      )

      if (containsInjection) {
        this.whereClauseError = '检测到不安全的SQL关键字，请修改WHERE条件'
        return false
      }

      // 基本语法检查
      try {
        // 检查括号是否匹配
        const openBrackets = (this.form.whereClause.match(/\(/g) || []).length
        const closeBrackets = (this.form.whereClause.match(/\)/g) || []).length

        if (openBrackets !== closeBrackets) {
          this.whereClauseError = '括号不匹配，请检查'
          return false
        }

        // 检查引号是否匹配
        const singleQuotes = (this.form.whereClause.match(/'/g) || []).length
        if (singleQuotes % 2 !== 0) {
          this.whereClauseError = '单引号不匹配，请检查'
          return false
        }

        // 检查基本逻辑结构
        const operatorPattern = /(=|!=|<>|>|<|>=|<=|LIKE|IN|IS NULL|IS NOT NULL)/i
        const logicalPattern = /(AND|OR|NOT)/i

        // 分割条件
        const conditions = this.form.whereClause.split(new RegExp(`\\s+(${logicalPattern.source})\\s+`, 'i'))

        for (const condition of conditions) {
          // 忽略纯逻辑运算符
          if (logicalPattern.test(condition) && condition.trim().length <= 5) {
            continue
          }

          // 检查每个条件是否包含运算符
          if (!operatorPattern.test(condition)) {
            this.whereClauseError = `条件 "${condition.trim()}" 缺少有效的比较运算符`
            return false
          }
        }

        // 验证通过
        this.whereClauseError = ''
        return true
      } catch (error) {
        console.error('WHERE条件验证出错', error)
        this.whereClauseError = '条件语法错误，请检查'
        return false
      }
    }
  }
}
</script>
<style scoped>
.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: end;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.el-table th{
  vertical-align: middle;
  line-height: 60px;
}

.data-collect-list {
  width: 100%;
  padding: 0;
  margin: 0;
}

.data-collect-list >>> .el-table th {
  height: 100px;
  line-height: 100px;
  vertical-align: middle;
  padding: 0;
}
</style>
